package algorithms.leaning.class33;

import common.util.MyUtil;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
 * 各种哈希函数
 * 生成任意哈希函数：已知两个哈希函数 f1、f2，则第i个哈希函数为 f = i * f1 + f2
 *
 * @author guichang
 * @date 2021/7/5
 */

@SuppressWarnings("all")
public class Code1_Hash_各种哈希函数 {

    public static void main(String[] args) {
        String input1 = "zuochengyunzuochengyun1";
        String input2 = "zuochengyunzuochengyun2";
        String input3 = "zuochengyunzuochengyun3";
        String input4 = "zuochengyunzuochengyun4";
        String input5 = "zuochengyunzuochengyun5";
        Security.getAlgorithms("MessageDigest").forEach(algorithm -> {
            MyUtil.print("当前哈希函数: " + algorithm);
            Hash hash = new Hash(algorithm);
            MyUtil.print(hash.hashCode(input1));
            MyUtil.print(hash.hashCode(input2));
            MyUtil.print(hash.hashCode(input3));
            MyUtil.print(hash.hashCode(input4));
            MyUtil.print(hash.hashCode(input5));
            MyUtil.print("=======");
        });
    }


    public static class Hash {
        private MessageDigest hash;

        public Hash(String algorithm) {
            try {
                hash = MessageDigest.getInstance(algorithm);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }

        public String hashCode(String input) {
            //return DatatypeConverter.printHexBinary(hash.digest(input.getBytes())).toUpperCase();
            return DatatypeConverter.printHexBinary(hash.digest(input.getBytes()));
        }
    }
}